package com.example.miaosha.service.impl;

import com.example.miaosha.entity.Promo;
import com.example.miaosha.mapper.PromoMapper;
import com.example.miaosha.service.ItemService;
import com.example.miaosha.service.PromoService;
import com.example.miaosha.service.model.ItemModel;
import com.example.miaosha.service.model.PromoModel;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * Created by lerry_li on 2020/10/22
 */
@Service
public class PromoServiceImpl implements PromoService {

    @Autowired
    private PromoMapper promoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ItemService itemService;

    @Override
    public PromoModel getPromoByItemId(Integer itemId) {
        //获取对应商品的秒杀活动信息
        Promo promo = promoMapper.selectByItemId(itemId);

        //entity->model
        PromoModel promoModel = convertModelFromEntity(promo);
        if (promoModel == null) {
            return null;
        }
        //判断对应商品的秒杀活动状态
        DateTime now = new DateTime();
        //1未开始,2进行中，3已结束
        if (promoModel.getStartTime().isAfterNow()) {
            System.out.println(promoModel.getPromoName()+" 秒杀活动未开始");
            promoModel.setStatus(1);
        } else if (promoModel.getEndTime().isBeforeNow()) {
            System.out.println(promoModel.getPromoName()+" 秒杀活动已结束");
            promoModel.setStatus(3);
        } else {
            System.out.println(promoModel.getPromoName()+" 秒杀活动进行中");
            promoModel.setStatus(2);
        }

        return promoModel;
    }

    @Override
    public void publishPromo(Integer promoId) {
        //通过活动id获取活动
        Promo promo= promoMapper.selectByPrimaryId(promoId);
        if(promo.getItemId()==null||promo.getItemId().intValue()==0){
            return;
        }
        ItemModel itemModel=itemService.getItemById(promo.getItemId());

        //将库存同步到redis
        redisTemplate.opsForValue().set("promo_item_stock_"+itemModel.getId(),itemModel.getStock());
    }

    private PromoModel convertModelFromEntity(Promo promo) {
        if (promo == null) {
            return null;
        }
        PromoModel promoModel = new PromoModel();
        BeanUtils.copyProperties(promo,promoModel);

        promoModel.setPromoItemPrice(BigDecimal.valueOf(promo.getPromoItemPrice()));
        promoModel.setStartTime(new DateTime(promo.getStartTime()));
        promoModel.setEndTime(new DateTime(promo.getEndTime()));

        return promoModel;
    }
}
